<template>
	<view>
		<u-switch :loading="loading" v-model="switchState" @change="handleSwitchChange()"></u-switch>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loading: true,
				switchState: false,
				subscription: {
					topic: '/light/light1/state',
					qos: 0
				},
				publish: {
					topic: '/light/light1/control',
					payload: {
						state: ''
					},
					qos: 0
				}
			}
		},
		methods: {
			handleSwitchChange() {
				if (this.switchState) {
					this.publish.payload.state = "ON"
					this.doPublish(this.publish)
				} else {
					this.publish.payload.state = "OFF"
					this.doPublish(this.publish)
				}
			},
			doPublish(message) {
				message.payload = JSON.stringify(message.payload)//mqtt的payload只能是字符串
				this.mqtt.publish(message.topic,message.payload,message.qos)
				message.payload = JSON.parse(message.payload)//mqtt发送完payload需要再转成对象使得下一次的值可以修改
			}
		},
		onLoad() {
			this.mqtt.subscribe(this.subscription.topic, this.subscription.qos)
			this.mqtt.on('message', (topic, message) => {
				message = JSON.parse(message)
				switch(message.state) {
					case 'ON':
						this.loading = false
						this.switchState = true
						break;
					case 'OFF':
						this.loading = false
						this.switchState = false
						break;
				}
			})
		},
		onUnload() {
			this.mqtt.unsubscribe(this.subscription.topic)
		}
	}
</script>
<style>

</style>